package com.huhao.wshare.config;

import com.huhao.wshare.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final UserDetailsService userDetailsService; // Spring会自动注入我们上面创建的 UserDetailsServiceImpl

    @Override
    protected void doFilterInternal(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull FilterChain filterChain
    ) throws ServletException, IOException {

        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        final String userAccount;

        // 1. 如果没有 Authorization 头或者不是以 "Bearer " 开头，直接放行
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 2. 提取 JWT
        jwt = authHeader.substring(7); // "Bearer ".length() == 7

        // 3. 从 JWT 中提取用户账号
        userAccount = jwtUtil.extractUsername(jwt);

        // 4. 如果用户账号存在，且当前安全上下文中没有认证信息
        if (userAccount != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 5. 加载用户详情
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(userAccount);

            // 6. 验证 token 是否有效
            if (jwtUtil.validateToken(jwt, userDetails.getUsername())) {
                // 7. 创建一个认证令牌
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails, // principal
                        null,       // credentials
                        userDetails.getAuthorities()
                );
                authToken.setDetails(
                        new WebAuthenticationDetailsSource().buildDetails(request)
                );
                // 8. 将认证信息设置到安全上下文中
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        // 9. 继续过滤器链
        filterChain.doFilter(request, response);
    }
}
